/*
 * GeoVISTA Center (Penn State, Dept. of Geography)
 * Copyright (c), 2003-2011,  Jin Chen and Alan M. MacEachren, GeoVISTA Center, Penn State University
 * All Rights Researved.
 *
 * This library is developed and distributed for free usage,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * You can redistribute and/or modify it under the terms of the
 * Simplified BSD License
 *
 *
 *
 *
 *
 *
 *  
 * @Original Author: jin Chen
 * @date: Aug 19, 2003$
 * @version: 1.0
 */
package edu.psu.geovista.app.dataloader.v1.gui;

import edu.psu.geovista.app.dataloader.v1.actions.PickCategoryAction;
import edu.psu.geovista.app.dataloader.v1.actions.SortAction;
import edu.psu.geovista.app.dataloader.v1.components.DataAssembler;
import edu.psu.geovista.app.pcp.toolkits.selectcontrol.SelectItemsPane;
import edu.psu.geovista.app.pcp.toolkits.selectcontrol.ui.VerticalBttnsPane;
import edu.psu.geovista.app.pcp.toolkits.table.ConfigureTableModel;
import edu.psu.geovista.common.awt.event.dataloading.TSEvent;
import edu.psu.geovista.common.awt.event.dataloading.TSListener;

import javax.swing.*;
import java.awt.*;
import java.util.Vector;

public class DataSelectPane extends SelectItemsPane {
   public static final String Btn_Select="  >  ";
   public static final String Btn_Deselect="  <  ";
   public static final String Btn_SelectAll=" >> ";
   public static final String Btn_DeselectAll=" << ";
   //public static final String Col_NumberOfRecord="Rows";
   public static final String Col_Name="Name";
   public static final String Col_Desc="Description";
   public static final String Col_Category="Category";
   public static final String Col_NumRec="Rows";

   //public static final String
   DataAssembler dataAssembler;
    private JCheckBox projectCheck;//if checked, means the data is projected one and need no more projection any more
    public DataSelectPane(){
        initLeftTable();
        initRightTable();
       setControlPane();

    }
    public DataSelectPane(DataAssembler dataAssembler) {
        this.dataAssembler=dataAssembler;
        initLeftTable();
        initRightTable();
        verifyApplyButton();
        setControlPane();

    }
    protected  void layoutComponents() {

        super.layoutComponents();

        setPreferredSize(new Dimension(500, 375));
    }
    protected void layoutTables() {
        layoutTable(TABLE_LEFT,new Dimension(373, 349),new Point(0,0),new Point(3,1));
        layoutTable(TABLE_RIGHT,new Dimension(273, 349),new Point(3,0),new Point(2,1));
    }
    public void initLeftTable() {
        Object[] arecord=new Object[]{"No data"," "};
        Object[][] data=new Object[][]{arecord};
        String[] names=new String[] {Col_Name,Col_Desc};
        this.setData(data,names);
        this.setColumnsWidth(new int[]{1,3},SelectItemsPane.TABLE_LEFT);
    }

    //1.create tableModel //2. init values
    protected void initRightTable() {
        //1. Model
        int initRowCount=0;
        Vector colNames =new Vector();
        colNames.add(Col_Name);colNames.add(Col_NumRec);
        Class[] types = new Class [] {
                 java.lang.String.class, java.lang.Integer.class
        };
        boolean[] editable={false,false,false};
        ConfigureTableModel model=new ConfigureTableModel(colNames,initRowCount);
        model.setTypes(types);
        model.setEditables(editable);
        this.rightTable.setModel(model);
        this.setColumnsWidth(new int[]{4,1}, SelectItemsPane.TABLE_RIGHT);
    }
    protected void initButtons() {
        //String[] names=new String[]{Btn_Select,Btn_SelectAll,Btn_Deselect,Btn_DeselectAll/*,"Apply"*/};
        //this.addButtons(names);
         VerticalBttnsPane selectP = createSelectBttnsPane();
          btnP.setLayout(new BorderLayout());
        btnP.add(selectP);

    }

    private void setControlPane(){
        JToolBar toolbar=new JToolBar();
        toolbar.setFloatable(false);
        toolbar.setPreferredSize(new Dimension(200,30));
        toolbar.setRollover(true);

        //pick category button
        JButton pickBtn =new JButton("pick");
        PickCategoryAction pickCtgAction=new PickCategoryAction("moveCategory",DataSelectPane.this,leftTable);
        pickCtgAction.setColumnName(DataSelectPane.Col_Category);
        //pickCtgAction.putValue(Action.NAME,"pick");//"moveCategory");//"pick");
        pickBtn.setAction(pickCtgAction);
        pickBtn.setToolTipText("Move a category to the top");
        pickBtn.setText(null);


        JButton sortBtn=new JButton();
        SortAction sortAct=new SortAction("sortColumn",DataSelectPane.this,leftTable);
        // sortAct.putValue(Action.NAME,"Sort");//"sortColumn");//"Sort");
        sortBtn.setAction(sortAct);
        sortBtn.setToolTipText("Sort data");
         sortBtn.setText(null);

        toolbar.add(pickBtn);
        toolbar.add(sortBtn);
        addToControlPane(toolbar);
    }
    protected void actOnButtonClick(String btnName) throws Exception {
        if(btnName.equals(Btn_Select) ){
            doSelect();

        }
        else if(btnName.equals(Btn_Deselect) ){
            doDeSelect() ;
        }
        else if(btnName.equals(Btn_SelectAll) ){
            this.doSelectAll();
        }
        else if(btnName.equals(Btn_DeselectAll) ){
            this.doDeSelectAll();
        }
        else if(btnName.equals("Apply")){
            this.doApply() ;

        }
        verifyApplyButton();
        /*else if(btnName.equals("DfTimeSeries")){
             doTs();

        }*/
    }
    /**
     *
     * @param data
     */
    public  void selectRecord(Object[] data) {
        String name=(String) data[0];//the ID (name of a attribute) of the record
        this.selectRecord(name);
        //To change body of implemented methods use File | Settings | File Templates.
    }

    /*******************************************************************************************************
     *                button actions
     *******************************************************************************************************/
    protected void doSelect(){
        this.moveRight();

    }
    protected void doSelectAll(){
        this.moveAllRight();
    }
    protected void doDeSelect(){
        this.moveLeft() ;

    }
    protected void doDeSelectAll(){
        this.moveAllLeft();

    }

    /**
     * set Apply button enable only if there are data selected
     */
    protected void verifyApplyButton(){
       int rowCount=rightTable.getRowCount();
       JButton applyBtn=this.getButton("Apply");
       if(applyBtn==null){
           return;
       }
       if(rowCount>1){
           applyBtn.setEnabled(true);
       }
       else{
           applyBtn.setEnabled(false);
       }
    }
    /**
     * load data to application
     * @throws Exception  if no data in rightTable, throw exception
     */
    public void doApply() throws Exception {
        String[] itemNames = getSelectedItemNames();
         if(itemNames==null||itemNames.length <=0){
             
            throw new Exception("Please select PCP data to load.");
        }
        if(dataAssembler!=null){
                this.dataAssembler.assembleData(itemNames);
                //clear
                this.dataAssembler.cleanData() ;
            }
            this.initLeftTable() ;
    }
    /**
     *
     * @return
     *
     */
    public String[] getSelectedItemNames() throws Exception {
        Object[] os= rightTable.getSortValueAtColumn("Name");
        String[] itemNames=new String[os.length ];
        for (int i=0;i<itemNames.length ;i++){
            itemNames[i]=(String)os[i];
        }

        return itemNames;
    }

    protected void doTs(){
           int row=this.rightTable.getSelectedRow();
              /* Only for database loading
              String attrName=(String) rightTable.getValueAt(row,"Name");
              this.updateTimeSeries(attrName);*/
            this.updateTimeSeries(null);
    }
    /*******************************************************************************************************
     *                support
     *******************************************************************************************************/
    /**
     * select a record on left table and add it to right table.
     * @param itemName  the record id
     */
    protected void selectRecord(String itemName) {
        int rowCount=0;
        if(dataAssembler!=null)
         rowCount=this.dataAssembler.getAttribute(itemName).size(); //see how many rows this column has
        Object[] arow={itemName, new Integer(rowCount) };
        this.rightTable.addRow(arow);
    }

    public void setDataAssembler(DataAssembler dataAssembler) {
        this.dataAssembler = dataAssembler;
    }
    /*******************************************************************************************************
     *                DfTimeSeries
     *******************************************************************************************************/
    public void addTsListener(TSListener l) {
        this.listenerList.add(TSListener.class,l);
    }
    public void removeTsListener(TSListener l) {
        this.listenerList.remove(TSListener.class,l);
    }
    public void updateTimeSeries(String axisName) {
       Object[] listeners=this.listenerList.getListenerList() ;
       TSEvent e=null;
       for (int i=listeners.length -2;i>=0;i-=2){
           if (listeners[i]== TSListener.class){
               e=new TSEvent(this,axisName);
               ((TSListener)listeners[i+1]).tsChange(e);
           }


       }
    }



}
